class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        set<string>hash(wordList.begin(),wordList.end());
        set<string>vis;
        if(beginWord==endWord)return 1;
        if(!hash.count(endWord))return 0;
        queue<string>q;
        q.push(beginWord);
        vis.insert(beginWord);
        int ret=1;
        while(q.size())
        {
            ret++;
            int sz=q.size();
            while(sz--)
            {
                string t=q.front();
                q.pop();
                for(int i=0;i<beginWord.size();i++)
                {
                    string tmp=t;
                    for(char ch='a';ch<='z';ch++)
                    {
                        tmp[i]=ch;
                        if(hash.count(tmp)&&!vis.count(tmp))
                        {
                            if(tmp==endWord)return ret;
                            q.push(tmp);
                            vis.insert(tmp);
                        }
                    }
                }
            }
        }
        return 0;
    }
};
